package org.example.filter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.example.dto.SelectUserRoleResultDto;
import org.example.entity.User;
import org.example.mapper.RoleMapper;
import org.example.mapper.UsersMapper;
import org.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    final JwtUtil jwtUtil;

    @Autowired
    final UsersMapper userMapper;

    @Autowired
    final RoleMapper roleMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = httpServletRequest.getRequestURI();
        //请求执行之前验证token
        //从请求中取出头部信息(token)
        //
        String authHeader = httpServletRequest.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            //没有头信息直接返回
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //有头信息继续工作
        String jwt = null;
        if (authHeader != null) {
            jwt = authHeader.substring(7);
        }
        if (jwtUtil.validateToken(jwt)) {
            //验证通过继续工作
            //构建一个认证Token对象

            String phone = jwtUtil.getUsernameFromToken(jwt);
            //从数据库中取出用户信息
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userMapper.selectOne(queryWrapper);

            if (user != null) {
                List<SelectUserRoleResultDto> roles = userMapper.selectUserRole(user.getPhone());
                //成功
                //构建一个认证Token对象
                UsernamePasswordAuthenticationToken Token = new UsernamePasswordAuthenticationToken(user,null,null);
                SecurityContextHolder.getContext().setAuthentication(Token);
            }

        }else{
            //失败
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        //继续工作
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
